<template>
  <div class="post-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索帖子标题/内容"
            clearable
            @clear="handleSearch"
          >
            <template #suffix>
              <el-icon class="el-input__icon" @click="handleSearch">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="帖子状态" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="已发布" value="published" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterType" placeholder="帖子类型" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="寻人启事" value="finding" />
            <el-option label="警方悬赏" value="police" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 修改表格容器和表格样式 -->
    <div class="table-container">
      <el-table 
        :data="filteredPosts" 
        v-loading="loading"
        height="calc(100vh - 250px)"
        style="width: 100%"
      >
        <el-table-column prop="nid" label="ID" width="80" />
        <el-table-column label="帖子信息" min-width="300">
          <template #default="scope">
            <div class="post-info">
              <div class="post-title">
                <el-tag v-if="scope.row.isTop" type="danger" size="small">置顶</el-tag>
                {{ scope.row.title }}
              </div>
              <div class="post-content">{{ scope.row.content }}</div>
              <div class="post-meta">
                <span>失踪人：{{ scope.row.author }}</span>
                <span>浏览：{{ scope.row.views }}</span>
                <span>评论：{{ scope.row.comments }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createdTime" label="发布时间" width="180" >
          <template #default="scope">
            {{formatDate(scope.row.createdDate)}}
          </template>
         </el-table-column>

        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
<!--            <el-button -->
<!--              v-if="scope.row.status === 'pending'"-->
<!--              type="success" -->
<!--              link -->
<!--              @click="handleApprove(scope.row)"-->
<!--            >-->
<!--              通过-->
<!--            </el-button>-->
<!--            <el-button -->
<!--              v-if="scope.row.status === 'pending'"-->
<!--              type="danger" -->
<!--              link -->
<!--              @click="handleReject(scope.row)"-->
<!--            >-->
<!--              拒绝-->
<!--            </el-button>-->
<!--            <el-button -->
<!--              type="primary" -->
<!--              link -->
<!--              @click="handleToggleTop(scope.row)"-->
<!--            >-->
<!--              {{ scope.row.isTop ? '取消置顶' : '置顶' }}-->
<!--            </el-button>-->
            <el-button type="primary" link @click="viewPost(scope.row)">
              查看
            </el-button>
            <el-button type="warning" link @click="closePost(scope.row)">
              关闭
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50,100,200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {changeNoteAPI, deleteNoteByNidAPI, getNotesByPageAPI} from "@/apis/notes";


// 数据结构修改
const postList = ref([])
const searchQuery = ref('')
const filterStatus = ref('')
const filterType = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 添加计算属性来筛选帖子
const filteredPosts = computed(() => {
  return postList.value.filter(post => {
    const matchesSearch = searchQuery.value 
      ? (post.title?.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
         post.content?.toLowerCase().includes(searchQuery.value.toLowerCase()))
      : true

    const matchesStatus = filterStatus.value 
      ? post.status === filterStatus.value
      : true

    // 添加类型筛选
    const matchesType = filterType.value
      ? post.type === filterType.value
      : true

    return matchesSearch && matchesStatus && matchesType
  })
})

// 获取帖子列表数据
async function fetchPosts() {
  loading.value = true
  try {
    const response = await getNotesByPageAPI(pageSize.value, currentPage.value)
    if (response.code === '200') {
      postList.value = response.data.list.map(item => ({
        nid: item.nid,
        title: item.title,
        content: item.describe || '暂无描述',
        author: item.seekerName,
        type: 'finding', // 根据实际数据映射
        status: item.status || 'published',
        createdDate: item.createdDate,
        // 其他字段映射
      }))
      total.value = response.data.total
    } else {
      postList.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取数据失败'+error)
  } finally {
    loading.value = false
  }
}

// 类型和状态相关方法
function getTypeTag(type) {
  const types = {
    finding: 'primary',
    police: 'danger'  // 警方悬赏使用红色标签
  }
  return types[type] || 'info'
}

function getTypeText(type) {
  const texts = {
    finding: '寻人启事',
    police: '警方悬赏'
  }
  return texts[type] || '未知'
}

function getStatusType(status) {
  const types = {
    pending: 'warning',
    published: 'success',
    closed: 'info'
  }
  return types[status] || 'info'
}

function getStatusText(status) {
  const texts = {
    pending: '待审核',
    published: '已发布',
    closed: '已关闭'
  }
  return texts[status] || '未知'
}

// 操作方法
function handleSearch() {
  currentPage.value = 1 // 重置页码
  fetchPosts() // 重新获取数据
}

function viewPost(row) {
  window.open(`http://localhost:5173/post/${row.nid}`, '_blank')
}

function closePost(row) {
  ElMessageBox.confirm(
      '确定关闭这篇帖子吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const newNote={
      nid:row.nid,
      status:1
    }
    const res=await changeNoteAPI(JSON.stringify(newNote))
    ElMessage({
      type:res.code==='200'?'success':'error',
      message:res.code==='200'?'帖子已关闭':res.msg
    })
    if(res.code==='200'){
      //刷新数据
      fetchPosts()
    }
  })
}

function handleDelete(row) {
  ElMessageBox.confirm(
    '确定要删除该帖子吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 实现删除逻辑
    await deleteNoteByNidAPI(row.nid).then(res=>{
      if(res.code==='200'){
        ElMessage.success('删除成功')
        fetchPosts()
      }else{
        ElMessage.error(res.msg)
      }
    })

  })
}

function formatDate(date) {
  const target=new Date(date)
  return `${target.toLocaleDateString()}`+` ${target.toLocaleTimeString()}`
}

function handleSizeChange(val) {
  pageSize.value = val
  // 重新加载数据
  fetchPosts()
}

function handleCurrentChange(val) {
  currentPage.value = val
  // 重新加载数据
  fetchPosts()
}

onMounted(() => {
  // 加载初始数据
  fetchPosts()
})
</script>

<style scoped>
.post-management {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.operation-area {
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  //overflow: hidden;
  //margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  //padding-bottom: 20px;
}

.post-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.post-title {
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.post-content {
  color: #666;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-meta {
  color: #999;
  font-size: 13px;
  display: flex;
  gap: 15px;
}

.el-select {
  width: 100%;
}
</style>
